import React, { useState, useEffect } from 'react';
import { Tree, Spin } from 'antd';
import type { DataNode } from 'antd/es/tree';
import axios from 'axios';
import { getDeptList } from '@/services/ant-design-pro/dept';

interface TreeNode extends DataNode {
  id: string;
  type?: 'department' | 'employee';
}

const AsyncTree = () => {
  const [treeData, setTreeData] = useState<TreeNode[]>([]);
  const [loading, setLoading] = useState(false);
  const [loadedKeys, setLoadedKeys] = useState<React.Key[]>([]);

  // 初始化加载根节点

  const fetchNodes = async (parentOrganizationCode: string) => {
    setLoading(true);
    try {
      const res = await getDeptList(
        parentOrganizationCode !== '0' ? { parentOrganizationCode: parentOrganizationCode } : {},
      );

      const formattedData = res.data.map((item: any) => ({
        id: item.organizationCode,
        key: item.organizationCode,
        title: item.govShortName,
        // isLeaf: !item.hasChildren,
      }));

      if (parentOrganizationCode === '0') {
        setTreeData(formattedData);
      } else {
        setTreeData((origin) => updateTreeData(origin, parentOrganizationCode, formattedData));
        setLoadedKeys((prev) => [...prev, parentOrganizationCode]);
      }
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchNodes('0');
  }, []);
  const updateTreeData = (list: TreeNode[], key: React.Key, children: TreeNode[]): TreeNode[] => {
    return list.map((node) => {
      if (node.key === key) {
        return { ...node, children };
      }
      if (node.children) {
        return { ...node, children: updateTreeData(node.children, key, children) };
      }
      return node;
    });
  };

  const onLoadData = async ({ key, children }: any) => {
    if (children || loadedKeys.includes(key)) return;
    console.log(key);
    await fetchNodes(key.toString());
  };

  return (
    <div style={{ width: '500.0px', height: '600.0px' }}>
      <Spin spinning={loading}>
        <Tree
          loadData={onLoadData}
          treeData={treeData}
          height={400}
          fieldNames={{ title: 'title', key: 'key', children: 'children' }}
        />
      </Spin>
    </div>
  );
};

export default AsyncTree;
